<!--//This file is part of the store/retrieve project
//    (http://code.google.com/p/storeretrieve/).
//
//    Store/retrieve is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    Store/retrieve is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with store/retrieve. If not, see <http://www.gnu.org/licenses/>.
//-->


<%@ page contentType="text/html; charset=UTF-8"%>
<html>

<%@ page
	import="java.util.Properties,
		java.util.List,
		java.util.ArrayList,
		java.io.File,
		java.io.FileInputStream,
		org.w3c.dom.*,
		javax.xml.parsers.*,
		javax.xml.xpath.*,
		java.util.HashMap,
		java.lang.StringBuilder,
		javax.xml.transform.dom.DOMSource,
		javax.xml.transform.stream.StreamResult,
		javax.xml.transform.Transformer,
		javax.xml.transform.TransformerFactory,
		javax.xml.transform.OutputKeys,
		java.util.Calendar,
		org.apache.commons.fileupload.*,
		org.apache.commons.fileupload.disk.*,
		org.apache.commons.fileupload.servlet.*,
		org.apache.commons.io.FileUtils,
		java.text.SimpleDateFormat,
		de.devcity.storeretrieve.Tools"%>

<%@include file="includes/backend.jsp"%>

<%! 	
	final static String GENERATOR = "Uploader Rev. 1";
	Properties props;
	String userMsg = "";

	File createContainerDirectory() {
		Calendar cal = Calendar.getInstance();
		String path = props.getProperty("INTERNAL_REPO_PATH") + "/" + 
			cal.get(Calendar.YEAR) + "/" + 
			fixLength(cal.get(Calendar.MONTH) + 1) + "/" + 
			fixLength(cal.get(Calendar.DAY_OF_MONTH)) + "/" + 
			(cal.getTime().getTime() / 1000) + "-" + 
			Tools.randomPathPart();
		File result = new File(path);
		try {
			result.mkdirs(); 
		} catch(Throwable ex) { 
			ex.printStackTrace();
		} finally {}	
		return result;
	}

	String fixLength(int i) {
		String result = "" + i;
		if(result.length() < 2)
			result = "0" + result;
		return result;
	}


	boolean createMetaXml(File containerDir, String id, String foreignId) {
		File file = new File(containerDir.getAbsolutePath() + "/meta.xml");
		Document doc = null;
		boolean success;
		
		try {
			DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
            		DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
            		Document newDoc = docBuilder.newDocument();
			Element container = newDoc.createElement("Container");
            		newDoc.appendChild(container);
			Element storage = newDoc.createElement("Storage");
			Element meta = newDoc.createElement("Meta");
			Element e;
			
			container.appendChild(storage);
		
			e = newDoc.createElement("Id");
			storage.appendChild(e);
			e.appendChild(newDoc.createTextNode(id));

			if(foreignId != null) {
		                e = newDoc.createElement("ForeignId");
		                storage.appendChild(e);
		                e.appendChild(newDoc.createTextNode(foreignId));
			}
			
                        e = newDoc.createElement("Generator");
                        storage.appendChild(e);
                        e.appendChild(newDoc.createTextNode(GENERATOR));

                        e = newDoc.createElement("Revision");
                        storage.appendChild(e);
                        e.appendChild(newDoc.createTextNode("1"));

			container.appendChild(meta);

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Calendar today = Calendar.getInstance();

                        e = newDoc.createElement("ImportDate");
                        meta.appendChild(e);
                        e.appendChild(newDoc.createTextNode(sdf.format(today.getTime())));

                        e = newDoc.createElement("Tags");
                        meta.appendChild(e);
                        e.appendChild(newDoc.createTextNode("NonIndexed"));

			DOMSource source = new DOMSource(newDoc);
			StreamResult result = new StreamResult(file);
			Transformer transformer = TransformerFactory.newInstance().newTransformer();
			transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
			transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
			
			transformer.setParameter("encoding", "UTF-8");
			transformer.transform(source, result);
			doc = newDoc;
			success = true;
		} catch(Throwable ex) { 
			success = false;
			ex.printStackTrace();
		} finally {}	


				
		return success;
	}

	String getUploadTableRows(int count) {
		StringBuilder o = new StringBuilder();
		if(count < 1) count = 1;
		if(count > 128) count = 128;
		
		for(int i = 0; i < count; i++) {
			o.append("<tr>");
			o.append("<td>File #" + (i+1));
			o.append("</td>");
			o.append("<td><input name=\"file\" type=\"file\" id=\"file" + i + "\" size=\"50\"></td>");
			o.append("</tr>");
		}
		
		return o.toString();
	}

%>

<%
	request.setCharacterEncoding("UTF-8");
	props = Tools.loadPropertiesByUser(getServletContext(), request.getRemoteUser());  

	if(props == null) {
		response.sendRedirect("login.jsp");
	} else {
		boolean success = false;
		boolean isUpload = false;

		String newId = java.util.UUID.randomUUID().toString(); //Fallback
		String newForeignId = null;
	   	List<FileItem> items = null;
		FileItemFactory factory = new DiskFileItemFactory();
	  	ServletFileUpload upload = new ServletFileUpload(factory);
		File container = null;
		int fileCount = 0;
	   	try {
			if(ServletFileUpload.isMultipartContent(request)) {
				items = Tools.castList(FileItem.class, upload.parseRequest(request));
				for(FileItem item : items) {
					 if(item.isFormField() && item.getFieldName().equals("origin") && item.getString().equals("upload")) isUpload = true;
				}
			} else isUpload = false;
		
			if(isUpload) {
				success = true;
				container = createContainerDirectory();
				for(FileItem item : items) {
					if (item.isFormField()) {
						if(item.getFieldName().equals("Id")) newId = item.getString();
						if(item.getFieldName().equals("ForeignId")) newForeignId = item.getString();
					} else {
						fileCount += 1;
						String itemName = item.getName();
						if(itemName.equals("meta.xml")) itemName = "meta-" + Tools.randomPathPart() + ".xml";
						File savedFile = new File(container.getAbsolutePath() + "/" + itemName);
						item.write(savedFile);
					}
				} 
			}
		} catch (Throwable e) {
			success = false;
			e.printStackTrace();
		}		

		if(isUpload) {
			if(success && fileCount == 0) {
				out.println("No files provided.");
				success = false;
			} 

			if(success) 
				success = createMetaXml(container, newId, newForeignId);


			if(success) {	
				out.println("<!-- RESULT: SUCCESS -->");
				out.println("<!-- COUNT: " + fileCount + " -->");
				out.println("<!-- ID: " + newId + " -->");
				userMsg = ("Saved " +  + fileCount + " files to ID <a href=\"edit.jsp?id=" + newId + "\">" + newId +"<a/>");
			} else {
				out.println("<!-- RESULT: ERROR -->");
				out.println("<!-- COUNT: -1 -->");
				out.println("<!-- ID: " + newId + " -->");
				FileUtils.deleteDirectory(container);
				userMsg = ("Error while saving " + newId);
			}
		} else {
			userMsg = ("Select upload file count: ");
			for(int c = 1; c <= 20; c++) {
				userMsg = userMsg + ("<a href=\"upload.jsp?count=" + c + "\">" + c + "</a>&nbsp;");
			}
		}
	}
%>

<head>
<title>store/retrieve upload client</title>
<link rel="stylesheet" type="text/css"
	href="resources/<%= props.getProperty("CSS") %>" />
<link rel="icon" href="resources/logo-storeretrieve-favicon.png"
	type="image/png" />
</head>
<body>
	<%= Tools.getLogoHtml() %>
	<p><%= userMsg %></p>
	<hr />
	<form>
		<table>
			<tr>
				<td>New ID</td>
				<td><input readonly="readonly" type="text" name="Id" size="50"
					value="<%= java.util.UUID.randomUUID() %>"></td>
			</tr>
			<tr>
				<td>Foreign ID</td>
				<td><input type="text" name="ForeignId" size="50" value=""></td>
			</tr>
			<%= getUploadTableRows((request.getParameter("count") == null) ? 1 : Integer.parseInt(request.getParameter("count"))) %>
		</table>
		<input type="hidden" name="origin" value="upload"> <input
			type="submit" value="Upload"> <input type="reset"
			value="Reset">
	</form>
</body>
</html>

